package com.example.tomcat;

//JAVA EE 9
//import jakarta.servlet.*;

//JAVA EE 8
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class MyServlet implements Servlet {

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("初始化");

        // 1、可以获取 Servlet 程序的别名 servlet-name 的值
        System.out.println("HelloServlet 程序的别名是:" + servletConfig.getServletName());
// 2、获取初始化参数 init-param
        System.out.println("初始化参数 username 的值是;" + servletConfig.getInitParameter("username"));
        System.out.println("初始化参数 url 的值是;" + servletConfig.getInitParameter("url"));
// 3、获取 ServletContext 对象
        System.out.println(servletConfig.getServletContext());
    /*
    HelloServlet 程序的别名是:MyServlet
    初始化参数 username 的值是;root
    初始化参数 url 的值是;null
    org.apache.catalina.core.ApplicationContextFacade@52a57e8a*/
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("MyServlet被调用");
        //类型转换
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        //获取请求方式
        String method = httpServletRequest.getMethod();
        if("POST".equals(method)){
            System.out.println("POST请求");
        }else if("GET".equals(method)){
            System.out.println("GET请求");
        }
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
        System.out.println("销毁");
    }

    public MyServlet() {
        System.out.println("构造器被调用");
    }
}
